package com.yoo.ons.function

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.yoo.ons.model.IMTokenModel
import com.yoo.ons.model.PolicyModel
import com.yoo.ons.model.UserInfoBaseModel
import com.yoo.chat.kit.RongIM
import com.yoo.chat.kit.conversationlist.ConversationListFragment
import com.yoo.chat.kit.manager.UnReadMessageManager
import com.yoo.chat.kit.userinfo.RongUserInfoManager
import com.yoo.chat.kit.userinfo.UserDataProvider
import com.yoo.chat.kit.utils.RongConfigUtil
import com.yoo.module_base.dialog.CustomPopup
import com.yoo.module_base.utils.SaveDeviceUtil
import com.yoo.module_base.utils.SystemInfoUtil
import com.yoo.ons.R
import com.yoo.ons.ToastUtil
import com.yoo.ons.base.BaseVMActivity
import com.yoo.ons.base.HttpRequestListener
import com.yoo.ons.databinding.ActivityMainBinding
import com.yoo.ons.event.MessageEvent
import com.yoo.ons.event.UserInfoEvent
import com.yoo.ons.function.home.HomeFragment
import com.yoo.ons.function.like.LikeListFragment
import com.yoo.ons.function.me.MeFragment
import com.yoo.ons.model.ConfigsEquityModel
import com.yoo.ons.model.ConversationInfoModel
import com.yoo.ons.model.ServerUserInfoModel
import com.yoo.ons.model.UserInfoModel
import com.yoo.ons.util.Injections
import io.rong.imlib.model.Conversation
import io.rong.imlib.model.UserInfo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


class MainActivity : BaseVMActivity<ActivityMainBinding, MainViewModel>(
    ActivityMainBinding::inflate,
    MainViewModel::class.java
) {
    val scope = MainScope()


    override fun initData() {
        initialViews()
    }

    private fun initialViews() {
        binding.viewPager.offscreenPageLimit = 4
        binding.viewPager.isScrollable = false
        binding.viewPager.adapter = object :
            FragmentPagerAdapter(supportFragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
            override fun getCount(): Int = 4
            override fun getItem(position: Int): Fragment {
                return when (position) {
                    0 -> HomeFragment()
                    1 -> LikeListFragment()
                    2 -> ConversationListFragment()
                    else -> MeFragment()
                }
            }
        }

        binding.navigation.attach(binding.viewPager)
        binding.navigation.setListener(object : NavigationLayout.Callback {
            override fun onItemClick(position: Int): Boolean {
                binding.viewPager.setCurrentItem(position, false)
                return false
            }

            override fun onItemClickAgain(position: Int) {
            }
        })

        mViewModel?.showTabLiveData?.observe(this) {
            binding.navigation.visibility = if (it) View.VISIBLE else View.GONE
        }

        //请求token，连接融云
        mViewModel?.getIMToken(object : HttpRequestListener<IMTokenModel>() {
            override fun addRequestParams(params: HashMap<String, Any>) {

            }

            override fun success(t: IMTokenModel?) {
                t?.let { RongConfigUtil.connectIM(it.token, this@MainActivity) }
            }
        })
        //获取客服信息
        mViewModel?.getServer(object : HttpRequestListener<List<ServerUserInfoModel>>() {
            override fun addRequestParams(params: HashMap<String, Any>) {
                params["code"] = 1
            }

            override fun success(t: List<ServerUserInfoModel>?) {
                if (!t.isNullOrEmpty()) {
                    t.apply {
                        RongIM.getInstance().refreshUserInfoCache(
                            UserInfo(
                                t[0].userCode,
                                t[0].name,
                                Uri.parse(t[0].iocn)
                            )
                        )
                        SaveDeviceUtil.saveServiceUserCode(t[0].userCode)
                    }
                }
            }
        })

        //获取PPV开关
        mViewModel?.getEquityConfig(object : HttpRequestListener<ConfigsEquityModel>() {
            override fun addRequestParams(params: HashMap<String, Any>) {
                params["code"] = 3
            }

            override fun success(t: ConfigsEquityModel?) {
                t?.apply {
                    SaveDeviceUtil.savePPVSwitch(t.photoShowUnableFlag)
                }
            }
        })

        //获取wifi信息
        mViewModel?.getAddDeviceInfo(object : HttpRequestListener<String>() {
            override fun addRequestParams(params: HashMap<String, Any>) {
//                SystemInfoUtil.getGPS(mActivity)?.let { requestBody.add("gps", it) }

                if (SystemInfoUtil.isWifiEnabled(this@MainActivity)) {
                    if (SystemInfoUtil.getWifiList(this@MainActivity).isNotEmpty())
                        params["wifilist"] = SystemInfoUtil.getWifiList(this@MainActivity)
                }
                val systemInfo = JsonObject()
                val manufacturer = Build.MANUFACTURER
                systemInfo.addProperty("brand", manufacturer ?: Build.BRAND)//	品牌
                params["systeminfo"] = systemInfo
            }

            override fun success(t: String?) {
            }
        })

        //获取PPV开关
        mViewModel?.getConversationList(object :
            HttpRequestListener<List<ConversationInfoModel>>() {
            override fun addRequestParams(params: HashMap<String, Any>) {
            }

            override fun success(t: List<ConversationInfoModel>?) {
                t?.apply {
                    GlobalScope.launch(Dispatchers.IO) {
                        repeat(t.size) {
                            val json = Gson().toJson(t[it])
                            SaveDeviceUtil.saveConversationInfo(json, t[it].userCodeFriend)
                        }
                    }
                }
            }
        })

        setIMInfo()
        mViewModel?.userInfoLiveData?.observe(this) {

        }
        mViewModel?.getUserInfo(object : HttpRequestListener<UserInfoModel>() {
            override fun addRequestParams(params: HashMap<String, Any>) {
            }

            override fun success(t: UserInfoModel?) {
            }
        })


        getCheckLogOut()

    }

    /**
     * 回归用户
     */
    private fun getCheckLogOut() {
        mViewModel?.getCheckLogOut(object : HttpRequestListener<String>() {
            override fun addRequestParams(params: HashMap<String, Any>) {
                params["userCode"] = SaveDeviceUtil.getUserCode() ?: ""
            }

            override fun success(t: String?) {
                t?.let { showWelcomeBackPopup(it) }

            }

            override fun endRequest() {
                super.endRequest()
            }

        })
    }

    /**
     * 展示回归用户弹窗
     */
    fun showWelcomeBackPopup(content: String) {
        if (TextUtils.isEmpty(content)) {
            return
        }
        val dialog = CustomPopup(this)
            .setLayoutId(R.layout.popup_welcome_back)
            .setContent(R.id.popup_content, content)
            .show()
        Injections.mainHandler.postDelayed({ dialog.dismiss() }, 3000)

    }


    /**
     * 进行IM的相关配置
     */
    private fun setIMInfo() {
        //设置用户头像/昵称
        RongUserInfoManager.getInstance()
            .setUserInfoProvider(object : UserDataProvider.UserInfoProvider {
                override fun getUserInfo(userId: String?): UserInfo? {
                    userId?.let {
                        scope.launch {
                            mViewModel?.getUserInfoBase(object :
                                HttpRequestListener<UserInfoBaseModel>() {
                                override fun addRequestParams(params: HashMap<String, Any>) {
                                    params["userCode"] = userId
                                }

                                override fun success(t: UserInfoBaseModel?) {
                                    t?.apply {
                                        val userInfo = UserInfo(
                                            t.userCode,
                                            t.nickName,
                                            Uri.parse(t.avatarUrl)
                                        )
                                        RongUserInfoManager.getInstance()
                                            .refreshUserInfoCache(userInfo)
                                    }

                                }

                            })

                        }
                    }
                    return null
                }
            }, true)
        //设置未读消息
        UnReadMessageManager.getInstance()
            .addObserver(
                arrayOf(Conversation.ConversationType.PRIVATE)
            ) { count -> binding.navigation.setUnreadNum(count) }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: MessageEvent?) {
        when (event?.type) {
            1 -> {
                // 在子线程中修改 UserInfoModel 对象的值
                GlobalScope.launch(Dispatchers.IO) {
                    val userInfoModel = mViewModel?.userInfoLiveData?.value
                    userInfoModel?.let {
                        val userInfoEvent = event.value as UserInfoEvent
                        userInfoEvent.avatarUrl?.apply {
                            it.avatarUrl = this
                            SaveDeviceUtil.saveAvatarUrl(it.avatarUrl)
                        }
                        userInfoEvent.imagesV2?.apply {
                            it.imagesV2 = this
                        }
                        userInfoEvent.nickName?.apply {
                            it.nickName = this
                        }
                        userInfoEvent.birthday?.apply {
                            it.birthday = this
                        }
                        userInfoEvent.lookingFor?.apply {
                            it.lookingFor = this
                        }
                        userInfoEvent.inchHeight?.apply {
                            it.inchHeight = this
                        }
                        userInfoEvent.aboutMe?.apply {
                            it.aboutMe = this
                        }
                        userInfoEvent.interests?.apply {
                            it.interests = this
                        }
                        userInfoEvent.userWant?.apply {
                            it.userWant = this
                        }
                        userInfoEvent.youAccept?.apply {
                            it.youAccept = this
                        }
                        mViewModel?.userInfoLiveData?.postValue(it)
                    }
                }
            }

            2 -> {
                //切换到首页tab
                binding.navigation.select(0)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventBus.getDefault().register(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        scope.cancel()
        EventBus.getDefault().unregister(this)
    }

    private var mExitTime: Long = 0

    @SuppressLint("MissingSuperCall")
    override fun onBackPressed() {
        if (System.currentTimeMillis() - mExitTime > 2000) {
            ToastUtil.showToast("Press exit again!")
        } else {
            finish()
        }
        mExitTime = System.currentTimeMillis()
    }


    companion object {
        fun start(context: Context) {
            val intent = Intent(context, MainActivity::class.java)
            context.startActivity(intent)
        }
    }

}